package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TimeHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        try {
            // 获取当前服务器时间并格式化
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String content = "<!DOCTYPE html>\n" +
                    "<html>\n" +
                    "<head>\n" +
                    "    <title>Server Time</title>\n" +
                    "    <style>\n" +
                    "        body { font-family: Arial, sans-serif; margin: 40px; }\n" +
                    "        h1 { color: #333; }\n" +
                    "        .time { font-size: 24px; color: #007bff; font-weight: bold; }\n" +
                    "        .container { max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }\n" +
                    "        a { color: #007bff; text-decoration: none; }\n" +
                    "        a:hover { text-decoration: underline; }\n" +
                    "    </style>\n" +
                    "</head>\n" +
                    "<body>\n" +
                    "    <div class=\"container\">\n" +
                    "        <h1>MiniWebSvr Current Time</h1>\n" +
                    "        <p>Server Time: <span class=\"time\">" + currentTime + "</span></p>\n" +
                    "        <p><a href=\"/\">← Back to Home</a></p>\n" +
                    "    </div>\n" +
                    "</body>\n" +
                    "</html>";

            // 获取内容的字节数组，用于计算长度
            byte[] contentBytes = content.getBytes("UTF-8");

            // 构造完整的 HTTP 响应头和响应体
            StringBuilder header = new StringBuilder();
            header.append("HTTP/1.1 200 OK\r\n");
            header.append("Content-Type: text/html; charset=UTF-8\r\n");
            header.append("Content-Length: ").append(contentBytes.length).append("\r\n");
            header.append("Connection: close\r\n");
            header.append("\r\n");  // 空行分隔头部和正文

            // 先写入头部
            response.write(header.toString().getBytes("UTF-8"));
            // 再写入内容
            response.write(contentBytes);
            response.flush();

        } catch (IOException e) {
            System.err.println("Error in TimeHandler: " + e.getMessage());
            try {
                // 发生错误时返回500
                String errorContent = "<h1>500 Internal Server Error</h1><p>Error generating time response</p>";
                byte[] errorBytes = errorContent.getBytes("UTF-8");

                String errorHeader = "HTTP/1.1 500 Internal Server Error\r\n" +
                        "Content-Type: text/html; charset=UTF-8\r\n" +
                        "Content-Length: " + errorBytes.length + "\r\n" +
                        "Connection: close\r\n\r\n";

                response.write(errorHeader.getBytes("UTF-8"));
                response.write(errorBytes);
                response.flush();
            } catch (IOException ex) {
                System.err.println("Failed to send error response: " + ex.getMessage());
            }
        }
    }
}